const fs = require('fs');
const path = require('path');
const { docs } = require('./docs.js');
const { fileDisplay } = require('./fileDisplay.js');

const runSimplifyDoc = () => {
  const needReplace = docs
    .filter((item) => typeof item.id === 'object')
    .map((v) => {
      return {
        ...v.id,
        link: v.link,
      };
    });

  // 全文件搜索的路径
  const filePath = path.resolve('./src');

  // 先把docs里写了intl.get的还原成中文docs('xxx')，再匹配docs
  function simplifyDoc(curPath) {
    if (
      /src\\locale\\strings/.test(curPath) ||
      /utils\\locale/.test(curPath) ||
      /src\\utils\\docs/.test(curPath)
    ) {
      console.log('跳过文件：', curPath);
      // 跳过src/locale/string的检测, 跳过utils.locale的检测,跳过docs的检测
      return;
    }
    // if (!/src\\components\\crListItem/.test(curPath)) {
    //   return;
    // }
    let data = fs.readFileSync(curPath, 'utf-8');
    if (data.indexOf("import docs from 'utils/docs'") !== -1) {
      data = data.replace(
        /docs\([\s\r]*?intl\.get[\s\S]*?id:[\s\r]*?'(.*?)'[\s\S]*?defaultMessage:[\s\r]'(.*?)'[\s\S]*?\)[\s\S]*?\)/g,
        "docs('$2')",
      );
      needReplace.forEach((obj) => {
        const reg = new RegExp(`docs\\('${obj.defaultMessage}'\\)`, 'g');
        data = data.replace(reg, `docs('${obj.id}')`);
      });
      fs.writeFile(curPath, data, 'utf-8', (err) => {
        if (err) {
          console.log(err);
        } else {
          console.log('写入文件：', curPath);
        }
      });
    }
  }

  fileDisplay(filePath, simplifyDoc);
};

module.exports = {
  runSimplifyDoc,
};
